<template>
    <div class="Register">
        <div class="w1440">
            <div class="RegisterTit">
                <div class="tit">账号注册</div>
                <div class="text">已有账号 <router-link to="/login">去登录&gt;</router-link> </div>
            </div>
            <div class="RegisterBox">
                <el-form ref="formRef" :model="formData" :rules="formRules">
                    <div class="RegisterBoxCon">
                        <div class="item">
                            <!-- 姓名 -->
                            <el-form-item prop="realName">
                                <el-input v-model="formData.realName" placeholder="姓名" clearable />
                            </el-form-item>
                        </div>
                        <div class="item">
                            <el-form-item prop="healthStatus">
                                <el-select v-model="formData.healthStatus" placeholder="身体情况" clearable class="w100">
                                    <el-option v-for="item in healthStatusOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 密码 -->
                            <el-form-item prop="password">
                                <el-input type="password" v-model="formData.password" maxlength="20" placeholder="密码"
                                    clearable />
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 确认密码 -->
                            <el-form-item prop="confirmPassword">
                                <el-input type="password" v-model="formData.confirmPassword" maxlength="20"
                                    placeholder="确认密码" clearable />
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 电话 -->
                            <el-form-item prop="mobile">
                                <el-input v-model="formData.mobile" maxlength="11" placeholder="手机号码" clearable />
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 验证码 -->
                            <el-form-item prop="code">
                                <div class="captcha-container">
                                    <el-input v-model="formData.code" placeholder="验证码" style="width: 100%" />
                                    <el-button :disabled="isCountingDown" @click="sendCaptcha">
                                        {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
                                    </el-button>
                                </div>
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 身份证号码 -->
                            <el-form-item prop="idCard">
                                <el-input v-model="formData.idCard" placeholder="身份证号码" clearable />
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 政治面貌 -->
                            <el-form-item prop="politicalStatus">
                                <el-select v-model="formData.politicalStatus" placeholder="政治面貌" class="w100" clearable>
                                    <el-option v-for="item in politicalOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 学历 -->
                            <el-form-item prop="education">
                                <el-select v-model="formData.education" placeholder="学历" class="w100" clearable>
                                    <el-option v-for="item in educationOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 单位名称 -->
                            <el-form-item prop="company">
                                <el-input v-model="formData.company" placeholder="单位名称" clearable />
                            </el-form-item>
                        </div>
                        <div class="item">
                            <!-- 职位 -->
                            <el-form-item prop="position">
                                <el-input v-model="formData.position" placeholder="职位" clearable />
                            </el-form-item>
                        </div>
                    </div>
                    <el-form-item prop="privacyPolicy">
                        <el-checkbox v-model="formData.privacyPolicy"></el-checkbox>
                        <div class="agree">
                            我已阅读并接受
                            <el-link type="primary" @click="showPrivacyPolicy(1)">《用户注册与使用协议》</el-link>
                            及
                            <el-link type="primary" @click="showPrivacyPolicy(0)">《隐私保护协议》</el-link>
                        </div>

                    </el-form-item>

                    <!-- 提交按钮 -->
                    <el-form-item>
                        <el-button type="primary" @click="submitForm" class="submitBtn">提交</el-button>
                        <!-- <el-button @click="resetForm">重置</el-button> -->
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <!-- 弹出框 -->
        <el-dialog v-model="privacyAgreement.dialogVisible" :title="privacyAgreement.dialogTitle" width="800">
            <div class="privacy-content">
                {{ privacyAgreement.privacyAgreementContent() }}
            </div>
            <template #footer>
                <div class="dialog-footer t-center">
                    <el-button type="primary" @click="agreePrivacy">
                        <el-icon class="el-icon--left"><el-checkbox v-model="formData.privacyPolicy"
                                size="large" /></el-icon>
                        同意并接受相关协议
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup name="Register">
import { userApi } from '@/api';
import { computed, ref, reactive, onBeforeMount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

// 路由
const router = useRouter();

/**
 * 
 * @name 注册
 */
// 隐私协议弹窗控制
const privacyAgreement = reactive({
    dialogVisible: false,
    dialogTitle: '用户注册与使用协议',
    registerContent: '用户注册与使用协议内容',
    privacyContent: '隐私保护协议内容',
    privacyAgreementContent: () => { return this.registerContent },
})
// 表单
const formData = ref({
    realName: '',
    mobile: '',
    idCard: '',
    politicalStatus: '',
    education: '',
    company: '',
    position: '',
    healthStatus: '',
    code: '',
    privacyPolicy: false,
    password: '',
    confirmPassword: '',
})
// 表单验证规则
const validateConfirm = (rule, value, callback) => { // 确认密码验证规则
    if (value === '') {
        callback(new Error('请再次输入密码'));
    } else if (value !== formData.value.password) {
        callback(new Error('两次输入密码不一致!'));
    } else {
        callback();
    }
};
const formRules = reactive({
    realName: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
        { validator: validateConfirm, trigger: 'blur' }
    ],
    mobile: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
        }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        {
            pattern: /^\d{6}$/,
            message: '验证码为6位数字',
            trigger: 'blur'
        }
    ],
    idCard: [
        { required: true, message: '请输入身份证号码', trigger: 'blur' },
        {
            pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
            message: '请输入正确的身份证号码',
            trigger: 'blur'
        }
    ],
    politicalStatus: [{
        required: true,
        message: '请选择政治面貌',
        trigger: 'change'
    }],
    education: [{
        required: true,
        message: '请选择学历',
        trigger: 'change'
    }],
    company: [{
        required: true,
        message: '请输入单位名称',
        trigger: 'blur'
    }],
    position: [{
        required: true,
        message: '请输入职位',
        trigger: 'blur'
    }],
    healthStatus: [{
        required: true,
        message: '请输入身体情况',
        trigger: 'blur'
    }],

    privacyPolicy: [{
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请阅读并接受《用户注册与使用协议》及 《隐私保护协议》'))
            } else {
                callback()
            }
        },
        trigger: 'change'
    }]
})
// 政治面貌，1群众 2团员 3党员
const politicalOptions = reactive([
    { value: 1, label: '群众' },
    { value: 2, label: '团员' },
    { value: 3, label: '党员' },
])
// 学历，1高中及以下 2大专 3本科 4硕士 5博士
const educationOptions = reactive([
    { value: 1, label: '高中及以下' },
    { value: 2, label: '大专' },
    { value: 3, label: '本科' },
    { value: 4, label: '硕士' },
    { value: 5, label: '博士' },
])
// 身体情况，1健康 2残疾 3重大疾病
const healthStatusOptions = reactive([
    { value: 1, label: '健康' },
    { value: 2, label: '残疾' },
    { value: 3, label: '重大疾病' },
])
// 验证码倒计时
const countdown = ref(0);
// 验证码倒计时状态
const isCountingDown = ref(false);

/**
 * @name 方法
 */
// 同意协议
const agreePrivacy = () => {
    privacyAgreement.dialogVisible = false;
    formData.value.privacyPolicy = true;
}
// 发送验证码
const sendCaptcha = () => {
    // 验证手机号是否填写
    if (!formData.value.mobile) {
        ElMessage.warning('请先填写手机号码')
        return
    }
    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(formData.value.mobile)) {
        ElMessage.warning('请输入正确的手机号码')
        return
    }
    // 开始倒计时
    isCountingDown.value = true;
    countdown.value = 60;
    let timer = null;
    // 发送验证码
    if (!isCountingDown.value) return;
    userApi.sendSmsCode({ mobile: formData.value.mobile }).then(res => {
        // 模拟发送验证码
        ElMessage.success('验证码已发送，请注意查收');
        timer = setInterval(() => {
            countdown.value--;
            if (countdown.value < 0) {
                clearInterval(timer)
                isCountingDown.value = false;
            }
        }, 1000)
    }).catch(err => { });
}
// 提交注册表单
const formRef = ref(null);
const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            // 这里可以调用API提交表单数据
            userApi.register(formData.value).then(res => {
                ElMessage.success('注册成功');
                // 2秒后跳转首页
                setTimeout(() => {
                    router.push('/login')
                }, 2000)
            }).catch(err => { });
        } else {
            ElMessage.warning('请填写完整表单信息')
            return false
        }
    })
}
// 查看隐私协议
const showPrivacyPolicy = (type) => {
    // 这里实现显示隐私政策的逻辑
    if (type) {
        privacyAgreement.dialogTitle = '用户注册与使用协议';
        privacyAgreement.privacyAgreementContent = () => { return privacyAgreement.registerContent }
    } else {
        privacyAgreement.dialogTitle = '隐私保护协议';
        privacyAgreement.privacyAgreementContent = () => { return privacyAgreement.privacyContent }
    }
    privacyAgreement.dialogVisible = true;
}
</script>

<style lang="less" scoped>
.captcha-container {
    display: flex;
    align-items: center;
    width: 100%;
}

.RegisterBox .el-form {
    max-width: 850px;
    margin: 0 auto;
}

.RegisterBox .RegisterBoxCon {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
}

.RegisterBox .item {
    width: 400px;
}

.RegisterBox :deep(.el-form-item) {
    margin-bottom: 24px;
}

.RegisterBox .item :deep(.el-select__wrapper),
.RegisterBox .item :deep(.el-input__wrapper) {
    padding: 10px 20px;
    height: 50px;
}

.RegisterBox .item :deep(.el-cascader) {
    width: 100%
}

.RegisterBox .item :deep(.el-button) {
    width: auto !important;
    margin-left: 0 !important;
    position: absolute;
    right: 1px;
    color: #00753e;
    border: none;
    text-align: right;
    padding: 0 20px;
}

.RegisterBox .item :deep(.el-button:hover) {
    background-color: transparent !important;
}

.agree {
    display: flex;
    align-items: center;
    margin-left: 10px;
}

.RegisterBox :deep(.el-link__inner) {
    color: #00753E;
}

.submitBtn {
    width: 400px;
    height: 50px;
    background: #00753E;
    border-radius: 4px;
    border-color: #00753E;
    margin: 0 auto;
    margin-top: 10px;
}

.privacy-content {
    max-height: 600px;
    overflow-y: auto;
    overflow-x: hidden;
    min-height: 200px;
}
</style>